package com.shujia.flink.transform;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Demo01Map {
    public static void main(String[] args) throws Exception {
        /*
         * map操作：传入一条数据返回一条数据
         */

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();


        // 提取students中的name
        DataStream<String> studentDS = env.readTextFile("flink/data/students.txt");

        // 传入处理的逻辑三种方式：

        // 1、使用lambda表示式
        studentDS.map(stu -> stu.split(",")[1], Types.STRING).print();

        // 2、使用匿名内部类
        studentDS.map(new MapFunction<String, String>() {
            @Override
            public String map(String value) throws Exception {
                return value.split(",")[1];
            }
        }).print();

        // 3、使用自定义Function类
        studentDS.map(new MyMapFunction()).print();
        studentDS.map(new NameMapFunction()).print();

        // 通过flatMap提取name
        studentDS.flatMap((stu, out) -> {
            out.collect(stu.split(",")[1]);
        }, Types.STRING).print();

        env.execute();
    }
}

// 自定义类实现Function接口
class MyMapFunction implements MapFunction<String, String> {
    @Override
    public String map(String value) throws Exception {
        return value.split(",")[1];
    }
}
